/**
 * Reducer Common
 * Created by yangbajing(yangbajing@gmail.com) on 2016-11-7.
 */

/**
 * 合并newItem到state page 对象。如：state: {page: {content: [newItem, ...]}}
 * @param type
 * @param state
 * @param newItem
 * @param config
 * @return {*}
 */
export function mergeItemToPageState(type, state, newItem, config = {}) {
    let newState = state;
    const page = state.get(type);
    const newPage = mergeItemToPage(page, newItem, config);
    return newState.set(type, newPage);
}

const __MIP_CONFIG = {
    keyContent: 'content',
    keyId: 'id'
};
export function mergeItemToPage(page, newItem, config = {}) {
    const {keyContent, keyId} = {...__MIP_CONFIG, ...config};
    const imtContent = page.get(keyContent);
    if (!imtContent) {
        return page.set(keyContent, fromJS([newItem]));
    }

    const idx = imtContent.findIndex(item => item.get(keyId) === newItem.get(keyId));
    let newItemList = null;
    if (idx > -1) { // 存在更新
        newItemList = imtContent.set(idx, newItem);
    } else { // 不存在，插入到头部
        newItemList = imtContent.insert(0, newItem);
    }
    return page.set(keyContent, newItemList);
}

/**
 * 合并newItem到state list 对象。如：state: {list:[oldItem, ...]}
 * @param type
 * @param state
 * @param newItem
 * @param config
 */
export function mergeItemToListState(type, state, newItem, config = {}) {
    let newState = state;
    const list = state.get(type);
    const newList = mergeItemToList(list, newItem, config);
    return newState.set(type, newList);
}

export function mergeItemToList(imtList, newItem, config = {}) {
    const {keyId} = {...__MIP_CONFIG, ...config};
    if (!imtList) {
        return fromJS([newItem]);
    }

    const idx = imtList.findIndex(item => item.get(keyId) === newItem.get(keyId));
    let newList = null;
    if (idx > -1) {
        newList = imtList.set(idx, newItem);
    } else {
        newList = imtList.insert(0, newItem);
    }
    return newList;
}
